<template>
  <div class="app-container">
    <div class="search-container">
      <el-form v-show="showSearch" ref="queryParamsRef" :inline="true" :model="queryParams" label-width="100px">
        <el-form-item v-if="!userInfo.orgId" label="所属机构">
          <select-org-tree :value="queryParams.orgId" @orgNodeClick="orgNodeClick"/>
        </el-form-item>
        <el-form-item label="药品类别" prop="drugType">
          <drug-class :value="queryParams.drugTypeNameShow" class="width-120"
                      @org-node-click="drugTypeNodeClick"/>
        </el-form-item>
        <el-form-item label="药品分类" prop="drugClass">
          <el-select v-model="queryParams.drugClass" class="width-120" clearable placeholder="请选择药品分类"
                     @change="handleQuery">
            <el-option v-for="dict in dictDataMap['drug_classification']" :key="dict.dictValue"
                       :label="dict.dictLabel" :value="dict.dictValue"/>
          </el-select>
        </el-form-item>
        <el-form-item label="剂型" prop="drugFrom">
          <el-select v-model="queryParams.drugFrom" class="width-120" clearable filterable
                     placeholder="请选择剂型" @change="handleQuery">
            <el-option v-for="dict in dictDataMap['drug_form_dict']" :key="dict.dictValue"
                       :label="dict.dictLabel" :value="dict.dictValue"/>
          </el-select>
        </el-form-item>
        <el-form-item label="药品名称" prop="drugName">
          <el-input v-model="queryParams.itemInfo" clearable placeholder="药品名称、编码、拼音码"
                    @keyup.enter.native="handleQuery"/>
        </el-form-item>
        <!--        <el-form-item label="药品编码" prop="drugCode">-->
        <!--          <el-input v-model="queryParams.drugCode" clearable placeholder="请输入药品编码"-->
        <!--                    @keyup.enter.native="handleQuery"/>-->
        <!--        </el-form-item>-->
        <el-form-item label="基本药物类型" prop="basicDrugType">
          <el-select v-model="queryParams.basicDrugType" class="width-120" clearable
                     placeholder="请选择基本药物类型"
                     @change="handleQuery">
            <el-option v-for="dict in dictDataMap['basic_drug_type']" :key="dict.dictValue"
                       :label="dict.dictLabel" :value="dict.dictValue"/>
          </el-select>
        </el-form-item>
        <el-form-item label="毒理分类" prop="toxiProperty">
          <el-select v-model="queryParams.toxiProperty" class="width-120" clearable
                     placeholder="请选择毒理分类"
                     @change="handleQuery">
            <el-option v-for="dict in dictDataMap['drug_toxi_property_dict']" :key="dict.dictValue"
                       :label="dict.dictLabel" :value="dict.dictValue"/>
          </el-select>
        </el-form-item>
        <el-form-item label="限制等级" prop="limitClass">
          <el-select v-model="queryParams.limitClass" class="width-120" clearable placeholder="限制等级"
                     @change="handleQuery">
            <el-option v-for="dict in dictDataMap['limit_class_dict']" :key="dict.dictValue"
                       :label="dict.dictLabel" :value="dict.dictValue"/>
          </el-select>
        </el-form-item>
        <el-form-item label="抗菌药物" prop="antisepticType">
          <el-radio-group v-model="queryParams.antisepticType" @change="handleQuery">
            <el-radio value="">全部</el-radio>
            <el-radio v-for="dict in dictDataMap['sys_yes_no']" :key="dict.dictValue"
                      :value="dict.dictLabel">
              {{ dict.dictLabel }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <div class="mr20" style="float: right">
          <query-form-button @handleQuery="handleQuery" @resetQuery="resetQuery"/>
        </div>
      </el-form>
    </div>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-hasPerm="['base:drugInfo:add']" type="primary" @click="handleAdd">
          <template #icon>
            <i-ep-plus/>
          </template>
          新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPerm="['base:drugInfo:remove']" :disabled="multiple" plain type="danger"
                   @click="handleDelete">
          <template #icon>
            <i-ep-delete/>
          </template>
          删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          plain
          type="info"
          @click="handleImport"
        >
          <template #icon>
            <i-ep-upload/>
          </template>
          导入数据、导出模板
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button plain type="danger" @click="refreshCacheDrugInfoFun">
          <template #icon>
            <i-ep-refresh/>
          </template>
          刷新缓存
        </el-button>
      </el-col>
      <!--            <el-col :span="1.5">-->
      <!--                <el-button-->
      <!--                    type="warning"-->
      <!--                    plain-->
      <!--                    icon="el-icon-download"-->
      <!--                    -->
      <!--                    @click="handleExport"-->
      <!--                    v-hasPerm="['base:drugInfo:export']"-->
      <!--                >导出-->
      <!--                </el-button>-->
      <!--            </el-col>-->
    </el-row>

    <el-table v-adaptive :border="true" :data="drugInfoList" :header-cell-style="$headerCellStyle" :stripe="true"
              highlight-current-row>
      <el-table-column :align="'center'" :show-overflow-tooltip="true" label="药品分类" prop="drugClass">
        <template #default="scope">
          <dict-data-tag :options="dictDataMap['drug_classification']" :value="scope.row.drugClass"/>
        </template>
      </el-table-column>
      <el-table-column :align="'left'" :show-overflow-tooltip="true" label="药品类别" prop="drugTypeName"/>
      <el-table-column :align="'left'" :show-overflow-tooltip="true" label="药品剂型" prop="drugFromName"/>
      <el-table-column :align="'left'" :show-overflow-tooltip="true" fixed="left" header-align="center" label="药品名称"
                       prop="drugName"
                       width="220px">
        <template #default="scope">
          <span class="fz14 fw-bold">{{ scope.row.drugName }}</span>
        </template>
      </el-table-column>
      <el-table-column :align="'left'" :show-overflow-tooltip="true" fixed="left" header-align="center" label="药品别名"
                       prop="drugNameAlias"
                       width="220px">
        <template #default="scope">
          <span class="fz14 fw-bold">{{ scope.row.drugNameAlias }}</span>
        </template>
      </el-table-column>
      <el-table-column :align="'left'" :show-overflow-tooltip="true" fixed="left" label="药品编码" prop="drugCode"
                       width="110px"/>
      <el-table-column :align="'center'" :show-overflow-tooltip="true" label="毒理分类" prop="toxiPropertyName"/>
      <el-table-column :align="'center'" :show-overflow-tooltip="true" label="限制等级" prop="limitClassName">
        <template #default="scope">
          <dict-data-tag :options="dictDataMap['limit_class_dict']" :value="scope.row.limitClass"/>
        </template>
      </el-table-column>
      <el-table-column :align="'right'" :show-overflow-tooltip="true" label="剂量" prop="dose"/>
      <el-table-column :align="'left'" :show-overflow-tooltip="true" label="剂量单位" prop="doseUnitsName"/>
      <el-table-column :align="'right'" :show-overflow-tooltip="true" label="规格(含量)" prop="minSpec"
                       width="100px"/>
      <el-table-column :align="'left'" :show-overflow-tooltip="true" label="最小单位" prop="minUnitsName"/>
      <el-table-column :align="'right'" :show-overflow-tooltip="true" label="包装规格" prop="packageSpec"
                       width="130px"/>
      <el-table-column :align="'left'" :show-overflow-tooltip="true" label="包装单位" prop="packageUnitName"/>
      <el-table-column :align="'center'" :show-overflow-tooltip="true" label="最小单位规格" prop="minSpec"
                       width="100px"/>
      <el-table-column :align="'center'" :show-overflow-tooltip="true" label="包装数量" prop="packageNum"/>
      <el-table-column :align="'center'" :show-overflow-tooltip="true" label="拆分系数" prop="splitNum"/>
      <el-table-column :align="'center'" :show-overflow-tooltip="true" label="批准文号" prop="passNo"
                       width="160px"/>
      <el-table-column :align="'center'" :show-overflow-tooltip="true" label="基本药物类型" prop="basicDrugType"
                       width="90px">
        <template #default="scope">
          <dict-data-tag :options="dictDataMap['basic_drug_type']" :value="scope.row.basicDrugType"/>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" :show-overflow-tooltip="true" label="抗菌药物" prop="antisepticType">
        <template #default="scope">
          <dict-data-tag :options="dictDataMap['sys_yes_no']" :value="scope.row.antisepticType"/>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" :show-overflow-tooltip="true" label="自费或医保" prop="zfOrYb">
        <template #default="scope">
          <dict-data-tag :options="dictDataMap['is_medical_insurance']" :value="scope.row.zfOrYb"/>
        </template>
      </el-table-column>
      <el-table-column :align="'left'" :show-overflow-tooltip="true" label="国家医保名称" prop="countryYbName"
                       width="200px"/>
      <el-table-column :align="'left'" :show-overflow-tooltip="true" label="国家医保编码" prop="countryYbCode"
                       width="200px"/>
      <el-table-column :align="'left'" :show-overflow-tooltip="true" label="厂商名称" prop="firmName"
                       width="260px"/>
      <el-table-column :align="'center'" class-name="small-padding fixed-width" fixed="right" label="操作"
                       width="180px">
        <template #default="scope">
          <el-button v-hasPerm="['base:drugInfo:edit']" type="success" @click="handleUpdate(scope.row)">
            <template #icon>
              <i-ep-edit/>
            </template>
            修改
          </el-button>
          <el-button v-hasPerm="['base:drugInfo:remove']" type="danger" @click="handleDelete(scope.row)">
            <template #icon>
              <i-ep-delete/>
            </template>
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum"
                :total="total" @pagination="getList"/>
    <drug-add ref="drugAddRef" :drug-type-options="drugTypeOptions" :org-id="queryParams.orgId"
              @get-list-parent="getList()"/>

    <!-- 药品基本信息导入对话框 -->
    <el-dialog v-model="uploadOpen" :title="upload.title" append-to-body width="400px" @close="dialogClose">
      <el-upload ref="uploadRef" :auto-upload="false" :http-request="httpRequest" :limit="1"
                 :on-change="handleChange" :on-progress="handleFileUploadProgress" accept=".xlsx" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div slot="tip" class="el-upload__tip text-center">
          <span>仅允许导入xlsx格式文件。</span>
          <el-link :underline="false" style="font-size:12px;vertical-align: baseline;" type="primary"
                   @click="importTemplate">下载模板
          </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="dialogClose">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import {batchImport, delDrugInfo, refreshCacheDrugInfo, selectPageDrugInfo} from "@/api/drug/drugInfo";
import drugAdd from "@/views/drug/drugInfo/drugAdd.vue";
import {useUserStoreHook} from "@/store/modules/user";
import {useDictStoreHook} from "@/store/modules/dict";

const useUserStore = useUserStoreHook();
const {proxy} = getCurrentInstance() as any
const dictStore = useDictStoreHook();
const dictDataMap = ref(dictStore.isTypeGetData('is_medical_insurance', 'sys_yes_no', 'drug_form_dict', 'basic_drug_type', 'limit_class_dict',
  'drug_toxi_property_dict', 'drug_classification', 'spec_unit', 'price_ratio', 'dose_unit',
  'tally_subject_dict', 'outp_rcpt_fee_dict', 'inp_rcpt_fee_dict', 'spec_unit', 'reck_item_class_dict', 'mr_fee_class_dict'))
const drugAddRef = ref()
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo
// 选中数组
const ids = ref([])
// 非单个禁用
const single = ref(true)
// 非多个禁用
const multiple = ref(true)
// 显示搜索条件
const showSearch = ref(true)
// 总条数
const total = ref(0)
// 药品字典基本信息表格数据
const drugInfoList = ref([])
// 弹出层标题
const title = ref("")
// 药品类别字典
const drugClassDictAll = ref([])
// 药品类别树list
const drugTypeOptions = ref([])
// 查询参数
const queryParamsRef = ref()
const queryParams = ref<any>({
  pageNum: 1,
  pageSize: 10,
  drugId: undefined,
  drugType: undefined,
  drugTypeName: undefined,
  drugFrom: undefined,
  drugFromName: undefined,
  drugClass: undefined,
  drugClassName: undefined,
  drugName: undefined,
  drugInput: undefined,
  drugCode: undefined,
  drugStandardCode: undefined,
  sysDrugCode: undefined,
  toxiProperty: undefined,
  toxiPropertyName: undefined,
  limitClass: '',
  limitClassName: undefined,
  barCode: undefined,
  spec: undefined,
  packageSpec: undefined,
  packageUnits: undefined,
  packageUnitName: undefined,
  supplierId: undefined,
  supplierName: undefined,
  firmId: undefined,
  firmName: undefined,
  minSpec: undefined,
  minUnits: undefined,
  minUnitsName: undefined,
  packageNum: undefined,
  splitNum: undefined,
  dose: undefined,
  doseUnits: undefined,
  doseUnitsName: undefined,
  channel: undefined,
  performFreq: undefined,
  passNo: undefined,
  isOtc: '',
  gmp: '',
  basicDrugType: undefined,
  antisepticType: '',
  isPurchase: undefined,
  storageWay: undefined,
  orgId: undefined,
  remarks: undefined,
  remarks1: undefined,
  remarks2: undefined,
  remarks3: undefined,
  remarks4: undefined,
  auditState: '',
  countryYbName: undefined,
  countryYbCode: undefined,
  parentId: undefined,
  platformDrugInfo: undefined,
  highRisk: undefined,
  zfOrYb: '',
  drugTypeNameShow: undefined
})

const fileData = ref<any>(null)  // 文件上传数据（多文件合一）
const fileList = ref([])  // upload多文件数组
const uploadRef = ref()
//药品字典导入参数
const upload = ref<any>({
  // 弹出层标题
  title: "",
  // 是否禁用上传
  isUploading: false,

})
const uploadOpen = ref(false)

if (userInfo.orgId) {
  queryParams.value.orgId = userInfo.orgId
  getList()
}

// 机构树点击事件
function orgNodeClick(data, _e) {
  queryParams.value.orgId = data.orgId
  getList()
}

// 类别树树点击事件
function drugTypeNodeClick(data: any, _e) {
  queryParams.value.drugType = data.classCode
  // 查询条件回显
  queryParams.value.drugTypeNameShow = data.id
  getList()
}

/** 新增 */
function handleAdd() {
  if (!queryParams.value.orgId) {
    return ElMessage.error(proxy.$OrgIdIsEmpty)
  }
  drugAddRef.value.handleAdd()
}

/***/
function drugTypeNormalizer(node) {
  if (node.children && !node.children.length) {
    delete node.children;
  }
  return {
    id: node.classCode,
    label: node.className,
    children: node.children,
  };
}

/** 查询药品字典基本信息列表 */
function getList() {
  if (!queryParams.value.orgId) {
    return ElMessage.error(proxy.$OrgIdIsEmpty)
  }
  selectPageDrugInfo(queryParams.value).then((response: any) => {
    drugInfoList.value = response.rows;
    total.value = response.total;
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParamsRef.value.resetFields()
  queryParams.value.drugTypeNameShow = ''
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 导出按钮操作 */
function handleExport() {
  // download('base/DrugInfo/export', {
  //     ...queryParams
  // }, `drugInfo_${new Date().getTime()}.xlsx`)
}

/** 修改 */
function handleUpdate(row) {
  drugAddRef.value.handleUpdate(row)
}

/** 删除按钮操作 */
function handleDelete(row) {
  const idsThis = row.id || ids.value;
  ElMessageBox.confirm('是否确认删除药品字典基本信息编号为"' + idsThis + '"的数据项？',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    delDrugInfo(idsThis).then(() => {
      getList();
      ElMessage.success("删除成功");
    })
  }).catch(() => {
  })
}

function refreshCacheDrugInfoFun() {
  refreshCacheDrugInfo().then((res: any) => {
    ElMessage.success(res.msg);
  });
}

/** 导入按钮操作 */
function handleImport() {
  upload.value.title = "药品基本信息导入";
  uploadOpen.value = true;
}


/** 下载模板操作 */
function importTemplate() {
  // this.download('system/user/importTemplate', {}, `user_template_${new Date().getTime()}.xlsx`)
}


//监控上传文件列表
function handleChange(file, fileListInfo) {
  let existFile = fileListInfo.slice(0, fileListInfo.length - 1).find((f) => f.name === file.name)
  if (file.name.substring(file.name.lastIndexOf(".") + 1, file.name.length) !== 'xlsx') {
    fileListInfo.pop()
    return ElMessage.error('上传的文件类型不是.xlsx文件，请重新上传!')
  }
  if (existFile) {
    ElMessage.error('当前文件已经存在!')
    fileListInfo.pop()
  }
  fileList.value = fileListInfo
}

// 文件上传中处理
function handleFileUploadProgress(event, file, fileList) {
  upload.value.isUploading = true;
}


function httpRequest(file) {
  fileData.value.append('file', file.file) // append增加数据
}

function submitFileForm() {
  const link = document.createElement('a')
  fileData.value = new FormData() // new formData对象
  uploadRef.value.submit() // 提交调用uploadFile函数
  batchImport(fileData.value).then((res: resType) => {
    ElMessage.success("正在导入，请稍等...")
    setTimeout(() => {
      dialogClose()
    }, 5000)
    const blob = new Blob([res.data], {type: 'application/octet-stream'})
    link.download = "药品导入-错误数据.xlsx"
    let objectUrl = URL.createObjectURL(blob)
    link.href = objectUrl
    document.body.appendChild(link)
    // 下载文件
    link.click()
    // 释放内存
    window.URL.revokeObjectURL(objectUrl)
    document.body.removeChild(link)
  })
}

function dialogClose() {
  fileData.value = []
  fileList.value = []
  uploadRef.value.clearFiles()
  getList()
  uploadOpen.value = false;
}
</script>

<script lang="ts">
export default {
  name: "DrugInfo"
}
</script>
<style scoped>
:deep(.el-col) {
  margin-bottom: -2px;
}

:deep(.el-divider__text.is-left) {
  font-weight: bold;
  font-size: 19px;
}

:deep(.el-table .cell) {
  padding-left: 5px;
  padding-right: 5px;
}

:deep(.table-form-margin) > div {
  margin-left: 0 !important;
}

:deep(.requiredClass) > div.cell::before {
  content: "*";
  color: #f56c6c;
  margin-right: 4px;
}

:deep(.el-icon-plus) {
  margin-left: -2px;
}
</style>
